package com.xusheng.eduservice.controller;


import com.alibaba.excel.util.StringUtils;
import com.xusheng.commonutils.R;
import com.xusheng.eduservice.client.VodClient;
import com.xusheng.eduservice.entity.EduVideo;
import com.xusheng.eduservice.entity.chapter.ChapterVo;
import com.xusheng.eduservice.entity.chapter.VideoVo;
import com.xusheng.eduservice.service.EduVideoService;
import com.xusheng.servicebase.exceptionhandler.XushException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-01-12
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;
    @Autowired
    private VodClient vodClient;

    //课程大纲列表,根据课程ID进行查询
    /*@GetMapping("getChapterVideo/{v}")
    public R getChapterVideo(@PathVariable String courseId){
        List<ChapterVo> list = videoService.getVideoByCourseId(courseId);
        return R.ok().data("allChapterVideo",list);
    }*/
    @GetMapping("getVideo/{id}")
    public R getVideo(@PathVariable String id){
        List<VideoVo> list = videoService.getVideoById(id);
        return R.ok().data("Video", list);
    }
    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        videoService.save(eduVideo);
        return R.ok();
    }
    //删除小节
    // TODO 后面这个方法需要完善：删除小节时候，同时把里面视频删除
    /*@DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id){
        videoService.removeById(id);
        return R.ok();
    }*/
    @DeleteMapping("{videoId}")
    public R deleteVideo(@PathVariable("videoId") String videoId){
        //根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = videoService.getById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();

        //判断小节里面是否有视频id
        if(!StringUtils.isEmpty(videoSourceId)){
            //根据视频id，远程调用实现视频删除
            R result = vodClient.removeAlyVideo(videoSourceId);
            if(result.getCode() == 20001){
                throw new XushException(20001,"删除视频失败，熔断器...");
            }
        }

        //删除小节
        videoService.removeById(videoId);
        return R.ok();
    }
    //根据id查询小节信息
    @PostMapping("getVideoInfo/{videoId}")
    public R getVideoInfo(@PathVariable String videoId){
        EduVideo eduVideo = videoService.getById(videoId);
        return R.ok().data("eVideo",eduVideo);
    }

    //修改小节 TODO
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        videoService.updateById(eduVideo);
        return R.ok();
    }

}

